package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.*;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.MeasureType;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 反担保措施表基本表
 * BT_ITEM_ASSURE_SECURITY --》 nd_counter_guarantee_measures，nd_measure_details_table
 *
 *      自然人（法人）处理方式
 *      1：筛选非null的数据
 *      2：数据插到不同的表：101-自然人，1：法人(数据主键 (项目id+身份证,因为项目id)
 *      3：数据重复处理
 */
@BusinessDataConverter(
        insertSql =  "INSERT INTO ND_COUNTER_GUARANTEE_MEASURES(" +
                "ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS," +
                " MEASURE_TYPE, IS_FIX, FIX_TIME, ESTIMATE_VALUE, MEASURE_EXPLAIN, CHANGE_SIGN, IS_EFFECT, EXPIRE_TIME, FIX_EXPLAIN, PROJECT_ID, " +
                "REPLACE_NEWSTEP, MEASURE_DETAILS_ID, REVIEW_SIGN, FAX, ADDRESS, PROPERTY_CONTENT, CONTRACT_ID, PHONE, GENERATESTATE, REVOCATION_TIME, " +
                "BANKACCOUNTNO, DEPOSITBANK, PERCENTAGEOFPERFORMANCEAMOUNT, PERFORMANCERESERVE, RESERVEDEPOSITWORKINGDAY) VALUES" +
                "(?,?,?,?,?,?,?,?,?,?," +
                "?,?,?,?,?,?,?,?,?,?," +
                "?,?,?,?,?,?,?,?,?,?," +
                "?,?,?,?,?)",
        updateSql = "UPDATE ND_COUNTER_GUARANTEE_MEASURES SET CREATE_NAME = ?, CREATE_BY = ?, CREATE_DATE = ?, UPDATE_NAME = ?, UPDATE_BY = ?, " +
                "UPDATE_DATE = ?, SYS_ORG_CODE = ?, SYS_COMPANY_CODE = ?, BPM_STATUS = ?, " +
                "MEASURE_TYPE = ?, IS_FIX = ?, FIX_TIME = ?, ESTIMATE_VALUE = ?, MEASURE_EXPLAIN = ?, CHANGE_SIGN = ?, " +
                "IS_EFFECT = ?, EXPIRE_TIME = ?, FIX_EXPLAIN = ?, PROJECT_ID = ?, REPLACE_NEWSTEP = ?, MEASURE_DETAILS_ID = ?, " +
                "REVIEW_SIGN = ?, FAX = ?, ADDRESS = ?, PROPERTY_CONTENT = ?, CONTRACT_ID = ?, PHONE = ?, GENERATESTATE = ?, REVOCATION_TIME = ?, " +
                "BANKACCOUNTNO = ?, DEPOSITBANK = ?, PERCENTAGEOFPERFORMANCEAMOUNT = ?, PERFORMANCERESERVE = ?, RESERVEDEPOSITWORKINGDAY = ? WHERE ID = ? ",
        findMigratedIdListSql = " SELECT ID FROM ND_COUNTER_GUARANTEE_MEASURES WHERE PROJECT_ID = ?",
        seq = 201
)
public class NdCounterGuaranteeMeasures extends AbstractBusiness {

    public NdCounterGuaranteeMeasures(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId) throws SQLException {
        super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId);
    }


    @Override
    public void migrate() throws Exception {
        List<Map> btItemAssureSecurityList = this.sourceData.getBtItemAssureSecurityList();

        // 数据条件筛选 auditWorkflowNo IS NULL OR auditFlag = 2
//        List<Map> insertRowDatas = btItemAssureSecurityList.stream()
//                .filter(row -> (row.get("AUDITWORKFLOWNO") == null
//                        || row.get("AUDITWORKFLOWNO") == "")
//                        || "2".equals(row.get("AUDITFLAG").toString()))
//                .collect(Collectors.toList());

        // 反担保措施详情
        NdMeasureDetailsTable ndMeasureDetailsTable = new NdMeasureDetailsTable(sourceDbUtil,targetDbUtil,sourceData,programArgument,projectId);

        for (Map<String,Object> btItemAssureSecurity : btItemAssureSecurityList) {
            try {
                btItemAssureSecurity.put("measureDetailsId",buildId(btItemAssureSecurity));
                ndMeasureDetailsTable.customMigrate(btItemAssureSecurity);

            // 判断是否需要覆盖迁移
            int needMigratedResult = this.needMigrated(buildId(btItemAssureSecurity));
            if(needMigratedResult == 0) {
                continue;
            }


            // 单条插入或更新
            if(needMigratedResult == 1) {
                this.targetDbUtil.updateByParams(updateSql,this.buildValues(btItemAssureSecurity,ndMeasureDetailsTable),true);
            } else {
                this.targetDbUtil.updateByParams(insertSql,this.buildValues(btItemAssureSecurity,ndMeasureDetailsTable));
            }


            } catch(Exception e) {
                throw e;
            }

        }

//        ndMeasureDetailsTable.start();

    }

    /**
     * 构造数据主键
     * @param btItemAssureSecurity
     * @return
     */
    public String buildId(Map btItemAssureSecurity){
        // 基础表数据业务主键
        String originalId = btItemAssureSecurity.get("DATUMNO").toString();
        return originalId;
    }


    /**
     * 数据主键
     * @param btItemAssureSecurity
     * @return
     */
    public List buildValues(Map btItemAssureSecurity,NdMeasureDetailsTable ndMeasureDetailsTable){

        List<Object> value = new ArrayList<>();

        // 数据主键
        String id = buildId(btItemAssureSecurity);
        //        ID	主键
        value.add(id);
        //        CREATE_NAME	创建人名称
        value.add(null);
        //        CREATE_BY	创建人登录名称
        value.add(null);
        //        CREATE_DATE	创建日期
        value.add(null);
        //        UPDATE_NAME	更新人名称
        value.add(null);
        //        UPDATE_BY	更新人登录名称
        value.add(null);
        //        UPDATE_DATE	更新日期
        value.add(null);
        //        SYS_ORG_CODE	所属部门
        value.add(null);
        //        SYS_COMPANY_CODE	所属公司
        value.add("002");
        //        BPM_STATUS	流程状态
        value.add(null);


        //------------------ 处理反担保措施 主表只保存一级分类 -------------------
        String wayType = btItemAssureSecurity.get("WAYTYPE").toString();
        String oldDictName = BusinessTool.getOldDictDataNameByDictCodeAndDataCode("24", wayType);
        String measureType = "";
        // 如果包含-,则是二级分类
        if(oldDictName.contains("-")){
            String[] dictNameArray = oldDictName.split("-");
            measureType = DictTool.getTargetDictCode(MeasureType.class,dictNameArray[0]);
        }else{
            measureType = DictTool.getTargetDictCode(MeasureType.class,oldDictName);
        }
        //------------------ 处理反担保措施 end ---------------

        //        MEASURE_TYPE	反担保措施类别
        value.add(measureType);
        //        IS_FIX	是否落实
        value.add(btItemAssureSecurity.get("ISTRANSACT"));
        //        FIX_TIME	落实时间
        value.add(btItemAssureSecurity.get("VAILABLETIME"));
        //        ESTIMATE_VALUE	评估价值 旧系统无此数据
        value.add(null);

        //        MEASURE_EXPLAIN	措施说明
        Object  measureExplain = btItemAssureSecurity.get("TRANSACTMEMO");
        value.add(measureExplain == null ? null : Tool.replaceBrFlagStr(measureExplain.toString().substring(measureExplain.toString().indexOf("]") + 1)));

        //        CHANGE_SIGN	置换标记
        String replaceFlag = btItemAssureSecurity.get("REPLACEFLAG").toString();
        value.add(replaceFlag.equals("4") ? "3" : replaceFlag);
        //        IS_EFFECT	是否失效
        value.add("2".equals(btItemAssureSecurity.get("OVERTIMEFLAG").toString()) ? "not_expired" : "expired");
        //        EXPIRE_TIME	到期时间
        value.add(btItemAssureSecurity.get("OVERTIME"));

        //        FIX_EXPLAIN	落实情况说明
        Map<String,Object> itemBasic = this.sourceData.getBtItemBasic().get(0);
        value.add(Tool.replaceBrFlagStr(itemBasic.get("PLEDGECTLMEMO")));
        //        PROJECT_ID	项目ID
        value.add(this.projectId);


        //        REPLACE_NEWSTEP	反担保置换取消新增标记
        if(replaceFlag.equals("2") || replaceFlag.equals("4")) {
            value.add("replace");
        } else if(replaceFlag.equals("3")){
            value.add("newstep");
        } else {
            value.add(null);
        }

        //        MEASURE_DETAILS_ID	反担保措施详细信息表ID 旧系统使用一张表,新系统分两张表存储,此处使用同一个id
        value.add(ndMeasureDetailsTable.buildId(btItemAssureSecurity));
        //        REVIEW_SIGN	审核标志 空给1
        value.add(Tool.isEmpty(btItemAssureSecurity.get("AUDITFLAG")) ? "1" : btItemAssureSecurity.get("AUDITFLAG"));
        //        FAX	传真
        value.add(null);
        //        ADDRESS	住所
        value.add(btItemAssureSecurity.get("OWNERADDRESS"));
        //        PROPERTY_CONTENT	财产内容
        value.add(null);
        //        CONTRACT_ID	合同对应ID
        value.add(null);
        //        PHONE	电话
        value.add(btItemAssureSecurity.get("LINKTEL"));
        //        GENERATESTATE	合同是否生成
        value.add(null);
        //        REVOCATION_TIME	撤销时间
        value.add(null);


        //        BANKACCOUNTNO	履约准备金账号
        value.add(null);
        //        DEPOSITBANK	履约准备金银行
        value.add(null);
        //        PERCENTAGEOFPERFORMANCEAMOUNT	履约准备金占比
        value.add(null);
        //        PERFORMANCERESERVE	履约准备金数额
        value.add(null);
        //        RESERVEDEPOSITWORKINGDAY	履约准备金上缴限日
        value.add(null);
        return value;
    }

}
